﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MShop.Core.Domain;
using MShop.Core.Service;
using System.Web.Mvc;

namespace MShop.Core.DataAccess
{
    [Castle.Core.Transient(Lifestyle = Castle.Core.LifestyleType.Transient)]
    public class MenuDao :CommonDao<Menu>,IMenuDao
    {
        private readonly IRecursionSort<Menu> _RecursionService;
        private readonly IObjectContextProvider _Provider;
        public MenuDao(IObjectContextProvider provider, IRecursionSort<Menu> recursionservicce)
            : base(provider)
        {
            _Provider = provider;
            _RecursionService = recursionservicce;       
            
        }


        public override void Delete(Menu entity)
        {
            HashSet<Menu> hashset = new HashSet<Menu>();
            RecursiveMenus(entity, ref hashset);
            this.Delete(entity.MenuPage);
            foreach (var item in hashset)
            {
               
                var shopuserrights = item.ShopUserRights;
                var workspaces = item.WorkSpace;
                var powers = item.Powers;
                this.Delete((object)shopuserrights);
                this.Delete((object)workspaces);
                this.Delete((object)powers);
                base.Delete(item);
            }
        }


        private void RecursiveMenus(Menu menu, ref HashSet<Menu> hashset)
        { 
            hashset.Add(menu);
            foreach (var item in menu.Menu1)
            {
                RecursiveMenus(item, ref hashset);
            }
        }  
 

        #region IRecursionable<Menu> Members

        public IEnumerable<Menu> Build()
        {
            IList<Menu> list = new List<Menu>();
            int rowIndex = 1;
            _RecursionService.Recursion(GetAll(), ref list, ref rowIndex, null);
            return list;
        }

        public IList<System.Web.Mvc.SelectListItem> BuildSelectList(object selectedValue = null, bool includeRoot = false)
        {
            IList<SelectListItem> list = new List<SelectListItem>();

            foreach (var item in Build())
            {
                SelectListItem sitem = new SelectListItem();
                sitem.Value = item.Id.ToString();

                string line = "├";
                for (int i = 0; i < item.Depth; i++)
                {
                    line += "—";
                }
                sitem.Text = string.Concat(line, item.Name);
                list.Add(sitem);
            }
            if (includeRoot)
            {
                list.Insert(0, new SelectListItem() { Text = "根节点", Value = "" });
            }
            return list;
        }

        #endregion
    }
}